<?php
/**
 * 用户热点查询行为词条统计表基础业务
 * @author yxt 2013年1月16日12:16:59
 */
include_once dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . 'nl_common.func.php';
class nl_hot_search_count{
	/**
	 * 为热点词条累加1
	 * 没有热点词则添加一个
	 * @param $dc
	 * @param string $name
	 * @param string $type
	 * @param string $label_id
	 */
	static public function count_search_hot($dc,$name,$type,$label_id){
		$get_where=self::get_sql(array('name'=>$name,'type'=>$type,'label_id'=>$label_id));
		$sql="select * from nns_hot_search_count {$get_where}";
		$res=nl_query_by_db($sql, $dc->db());
		//如果没有查到结果,则需要插入
		if($res===true){
			$params=array('name'=>$name,'type'=>$type,'label_id'=>$label_id);
			$params["id"]=np_guid_rand();
			foreach ($params as $key=>$val){
				$field.="nns_{$key},";
				$values.="'{$val}',";
			}
			$field=trim($field,',');
			$values=trim($values,',');
			$sql="insert into nns_hot_search_count({$field}) values({$values})";
			$res=nl_execute_by_db($sql, $dc->db());
		}else if($res!==false){//如果查询成功则更新
			$sql="update nns_hot_search_count set nns_count=nns_count+1 {$get_where}";
			$res=nl_execute_by_db($sql, $dc->db());
		}
		return $res;
	}
	/**
	 * 修改于标签的同步状态
	 * @param $dc
	 * @param string $id
	 * @param string $label_id
	 * @param string $state 1同步0不同步
	 * @return bool
	 */
	Static public function update_hot_search_state_by_id ($dc,$id,$label_id,$state=1){
		if(empty($id)){
			return false;
		}
		$sql="update nns_hot_search_count set nns_label_id='{$label_id}',nns_state='{$state}' where nns_id='{$id}'";
		return nl_execute_by_db($sql, $dc->db());
	}
	
	/**
	 * 返回提供查询使用的where条件字符串
	 * @param $params:查询的一维字段=>值数组,不带前缀nns_
	 * @param $since起始页
	 * @param $num每页大小
	 * @param string $order :排序规则
	 * @param string $if_like:是否使用like查询，
	 * @param bool $log:字段之间的逻辑连接关系，默认为AND
	 * @retur string $sql:返回是的包含了"where"的条件语句
	 */
	static private function get_sql($params=array(),$since=null,$num=null,$order=null,$if_like=false,$log="AND"){
		if(empty($params)){
			$sql="";
		}else{
			$sql=" where ";
			if($if_like===false){
				foreach($params as $key=>$val){
					$sql.="nns_{$key}='{$val}' {$log} ";
				}
			}else{
				foreach($params as $key=>$val){
					$sql.="nns_{$key} like '%{$val}%' {$log} ";
				}
			}
			$sql=trim($sql,"{$log} ");
		}
		if(empty($since)){
			$limit=" ";
		}else{
			if(empty($num)){
				$limit=" limit {$since} ";
			}else{
				$limit=" limit {$since},{$num} ";
			}
		}
		if(!empty($order)){
			$order=self::$order[$order];
		}
		return $sql.$order.$limit;
	}
}
//$dc=nl_get_dc(array("db_policy"=>NL_DB_WRITE,"cache_policy"=>NP_KV_CACHE_TYPE_MEMCACHE));
//$dc->open();
////$r=hot_search_count::count_search_hot($dc, "aa", 1, "bb");
//$r=hot_search_count::update_hot_search_state_by_id($dc, "50faa08a1ea8654cc732fcd33cbea416", "aa",2);
//var_dump($r);